/*
 * @(#)Main.java  1.0  2011-08-15
 * 
 * Copyright (c) 2011 Werner Randelshofer, Goldau, Switzerland.
 * All rights reserved.
 * 
 * You may not use, copy or modify this file, except in compliance with the
 * license agreement you entered into with Werner Randelshofer.
 * For details see accompanying license terms.
 */
package org.monte.cmykdemo;

import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;
import javax.swing.SwingWorker;
import javax.swing.TransferHandler;
import org.monte.media.jpeg.CMYKJPEGImageReader;
import org.monte.media.jpeg.CMYKJPEGImageReaderSpi;

/**
 * Main.
 *
 * @author Werner Randelshofer
 * @version 1.0 2011-08-15 Created.
 */
public class Main extends javax.swing.JFrame {

    private Handler handler;

    /**
     * Creates new form Main
     */
    public Main() {
        initComponents();
        setSize(400, 300);

        String version = Main.class.getPackage().getImplementationVersion();
        if (version != null) {
            int p = version.indexOf(' ');
            setTitle(getTitle() + " " + version.substring(0, p == -1 ? version.length() : p));
        }


        handler = new Handler();
        setTransferHandler(handler);
        imageLabel.setTransferHandler(handler);
        //imageLabel.setBackground(Color.BLACK);
        //imageLabel.setOpaque(true);
        infoLabel.setTransferHandler(handler);
        scrollPane.setTransferHandler(handler);
        scrollPane.getViewport().setTransferHandler(handler);
    }

    /**
     * This method asynchronously loads an image file.
     */
    public void setFile(final File file) {
        imageLabel.setIcon(null);
        imageLabel.setText("Loading image...");

        new SwingWorker<BufferedImage, BufferedImage>() {
            @Override
            protected BufferedImage doInBackground() throws Exception {
                // Loads a JPEG image using the Java ImageIO API
                // ---------------------------------------------

                // The ImageIO API may provide many ImageReaders which
                // claim to be able to read the file. We try them all
                // out until we succeed.

                BufferedImage img = null;
                ImageInputStream iis = new FileImageInputStream(file);
                try {
                    CMYKJPEGImageReader r = new CMYKJPEGImageReader(new CMYKJPEGImageReaderSpi());
                    r.setInput(iis);
                    img = r.read(0);
                } finally {
                    iis.close();
                }
                return img;
            }

            @Override
            protected void done() {
                // Show the image or apologize in case of failure
                // -----------------------------------------------
                try {
                    BufferedImage image = get();
                    if (image == null) {
                        imageLabel.setText("Sorry. Couldn't load image.");
                        infoLabel.setText(null);
                    } else {
                        imageLabel.setIcon(new ImageIcon(image));
                        imageLabel.setText(null);
                        infoLabel.setText("<html>Image Dimension: "+image.getWidth()+" x "+image.getHeight()
                        +"<br>Color Model: "+image.getColorModel()
                        +"<br>has alpha: "+image.getColorModel().hasAlpha()+" is alpha premultiplied:"+image.getColorModel().isAlphaPremultiplied()
                                );
                    }
                } catch (Exception ex) {
                    imageLabel.setText("Sorry. Couldn't load image.");
                    ex.printStackTrace();
                }
                super.done();
            }
        }.execute();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        scrollPane = new javax.swing.JScrollPane();
        imageLabel = new javax.swing.JLabel();
        infoLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("MonteMedia CMYK Demo");

        scrollPane.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));

        imageLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        imageLabel.setText("Drop CMYK image here");
        scrollPane.setViewportView(imageLabel);

        getContentPane().add(scrollPane, java.awt.BorderLayout.CENTER);

        infoLabel.setFont(new java.awt.Font("Dialog", 0, 11)); // NOI18N
        getContentPane().add(infoLabel, java.awt.BorderLayout.PAGE_END);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel imageLabel;
    private javax.swing.JLabel infoLabel;
    private javax.swing.JScrollPane scrollPane;
    // End of variables declaration//GEN-END:variables

    /**
     * Transfer handler for drag and drop functionality.
     */
    private class Handler extends TransferHandler {

        @Override
        public boolean canImport(TransferSupport support) {
            return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
        }

        @Override
        public boolean importData(TransferSupport support) {
            try {
                List<File> files = (List<File>) support.getTransferable().getTransferData(DataFlavor.javaFileListFlavor);
                if (files.size() == 1) {
                    setFile(files.get(0));
                }
                return true;
            } catch (UnsupportedFlavorException ex) {
                ex.printStackTrace();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            return false;
        }
    }
}
